
; (function (w, doc) {
  const oBox = doc.querySelector('.container');
  const oCircle = oBox.querySelector('.circle');
  const oBar = doc.querySelector('.circle-bar');
  const oCircleHalfR = 320 / 2;
  const oCircleBorder = 10;
  const oBarHalfR = 30 / 2;
  function init() {
    let isDrag = false;
    let mouse_offset = {
      x: 0,
      y: 0
    }
    oBar.addEventListener('mousedown', e => {
      isDrag = true;
      mouse_offset = getMouseOffset(e)
    }, false)
    w.addEventListener('mousemove', e => {
      if (!isDrag) {
        return
      }
      mouse_offset = getMouseOffset(e)
      const radian = Math.atan2(mouse_offset.y, mouse_offset.x);
      const r = (oCircleHalfR - oCircleBorder / 2);
      const x = Math.cos(radian) * r;
      const y = Math.sin(radian) * r;
      oBar.style.left = oCircleHalfR + x - oBarHalfR + 'px';
      oBar.style.top = oCircleHalfR - (y + oBarHalfR) + 'px';
      updateContent(radian)
    }, false)
    w.addEventListener('mouseup', e => {
      isDrag = false
    }, false)


    function updateContent(radian) {
      let angle = radian * (180 / Math.PI);
      console.log(angle);
      if (angle >= -180 && angle < 90) {
        angle = 90 - angle;
      } else {
        angle = 360 - (angle - 90)
      }
      oCircle.textContent = Math.floor(angle)
    }

    function getMouseOffset(e) {
      const mouse_offsetX = e.clientX - oBox.offsetLeft - oCircleHalfR;
      const mouse_offsetY = - (e.clientY - oBox.offsetTop - oCircleHalfR);
      return {
        x: mouse_offsetX,
        y: mouse_offsetY
      }
    }

  }
  init()
})(window, document)